<template>
  <div class="device-tree-table">
    <!-- 顶部搜索 -->
     
    <AssessmentDialog
      v-model:visible="dialogVisible"
      :mode="dialogMode"
      :rowData="currentRow"
      @success="loadAllDevices"
    />
    <SearchFilters @search="onSearch" />

    <!-- 树形表格 -->
    <el-table
      v-if="treeRows.length"
      :data="treeRows"
      row-key="id"
      :tree-props="{ children: 'children' }"
      border
      height="600"
      style="width: 100%"
    >
      <el-table-column prop="name" label="设备名称" min-width="220" />
      <el-table-column prop="code" label="编码" width="160" />
      <el-table-column prop="specification" label="规格" width="160" />
      <el-table-column prop="material" label="材质" width="160" />

      <el-table-column prop="nodeType" label="类型" width="110">
        <template #default="{ row }">
          <el-tag size="small" :type="tagType(row.nodeType)">
            {{  typeLabel(row.nodeType)}} 
            
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <!-- <el-button type="primary" link size="small" @click="openEdit(row)">
            修改
          </el-button> -->
          <el-button type="success" link size="small" @click="openEdit(row)">
            评估
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <el-empty v-else description="暂无数据" class="empty-block" />

    <!-- 分页 -->
    <div class="tree-pagination" v-if="totalRoots > pageSize">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper, sizes"
        :total="totalRoots"
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5,10,20,50]"
        @current-change="noop"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import SearchFilters from './SearchFilters.vue'
import { listSbtz } from '@/api/sbtz/sbtz'
import AssessmentDialog from '@/components/sbtz/assessment/AssessmentDialog.vue'

const allRoots = ref([])
const fullData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const totalRoots = ref(0)


const dialogVisible = ref(false)
const dialogMode = ref('add')
const currentRow = ref({})

function openAdd(row) {
  dialogMode.value = 'add'
  dialogVisible.value = true
}

function openEdit(row) { 
  console.log('openEdit')
  console.log(row)
  currentRow.value = row
  dialogMode.value = 'edit'
  dialogVisible.value = true
}

// === 类型映射：英文转中文 ===
function typeLabel(type) {
  const map = {
    SYSTEM: '系统',
    MACHINE: '母设备',
    MODULE: '子设备',
    COMPONENT: '部件',
    PART: '零件',
    SPARE: '备件',
  };
  return map[type] || '备件';
}

function tagType(type) {
  const map = {
    MACHINE: 'primary',
    MODULE: 'success',
    SPARE: 'warning', 
  };
  return map[type] || 'warning'; 
}

/** 初始化加载完整数据 */
async function loadAllDevices() {
  const { rows = [] } = await listSbtz({ pageNum: 1, pageSize: 5000 })
  const filtered = rows.filter(r => r.nodeType !== 'SYSTEM')
  const map = new Map()
  filtered.forEach(f => map.set(f.id, { ...f, children: [] }))
  const roots = []
  filtered.forEach(f => {
    const cur = map.get(f.id)
    if (!f.parentId || !map.has(f.parentId)) roots.push(cur)
    else map.get(f.parentId).children.push(cur)
  })
  roots.forEach(d => attachRealSpares(d))
  // console.log(roots)
  fullData.value = roots
  allRoots.value = roots
  totalRoots.value = roots.length
}



/** 调整 spareInfos 结构：把 id 改成 spareId */
function attachRealSpares(node) {
  if (!node) return;

  // 确保 children 存在（树用它渲染）
  node.children = Array.isArray(node.children) ? node.children : [];

  // 1) 把 spareInfos 作为“备件子节点”挂到 children
  const spares = Array.isArray(node.spareInfos) ? node.spareInfos : [];
  if (spares.length) {
    const existingIds = new Set(node.children.map(c => String(c.id)));

    spares.forEach((s, idx) => {
      const spareId = s.spareId ?? s.id ?? `${node.id}-s${idx}`;
      const childId  = `spare:${node.id}:${spareId}`; // 保证唯一，不与设备 id 冲突
      if (existingIds.has(childId)) return;

      node.children.push({
        ...s,
        id: childId,          // 供树渲染
        spareId: spareId,     // 业务字段
        nodeType: 'SPARE',    // 标识为备件
        assetId: node.id,     // 记录父设备 id
        // 不再递归：备件为叶子
      });
    });
  }

  // 2) 递归真正的设备子节点（跳过备件）
  node.children.forEach(ch => {
    if (ch && ch.nodeType !== 'SPARE') attachRealSpares(ch);
  });
}

 







/** 模拟备件 + 通用列 */
function attachMockSpares(node) { 
  if (node.nodeType === 'SPARE') return
  node.children = node.children || []

  node.spareInfos = [
    {
      id: node.id + '-s1',
      name: '传感器',
      code: 'SP001',
      specification: 'Φ10×2cm',
      material: '不锈钢',
      nodeType: 'SPARE'
    },
    {
      id: node.id + '-s2',
      name: '电机',
      code: 'SP002',
      specification: '220V/1.5kW',
      material: '铝合金',
      nodeType: 'SPARE'
    }
  ]

  node.children.push(...node.spareInfos)
  node.children.forEach(child => {
    if (child.nodeType !== 'SPARE') attachRealSpares(child)
  })
}

/** 搜索 */
/** 搜索 */
/** 搜索（最小修复后的版本） */
async function onSearch(params) {
  // 1) 无条件 → 直接恢复完整树（fullData 已经是树，不要再 buildTree）
  if (!params.muName && !params.keyword) {
    allRoots.value = fullData.value
    totalRoots.value = allRoots.value.length
    return
  }

  // 2) 第一次查：匹配的母设备
  const { rows: matched = [] } = await listSbtz({
    id: params.muName || null,
    keyword: params.keyword || null,
    pageNum: 1,
    pageSize: 1000
  })
  if (!matched.length) {
    allRoots.value = []
    totalRoots.value = 0
    return
  }

  // 3) 第二次查：全量数据（前端拼完整子级）
  const { rows: all = [] } = await listSbtz({ pageNum: 1, pageSize: 5000 })
  const allFiltered = all.filter(r => r.nodeType !== 'SYSTEM')

  // 用 id 去重更稳妥
  const idSet = new Set()
  const result = []

  function addNodeById(id) {
    if (idSet.has(id)) return
    const node = allFiltered.find(n => n.id === id)
    if (!node) return
    idSet.add(id)
    result.push(node)
    // 递归孩子
    allFiltered
      .filter(n => n.parentId === id)
      .forEach(ch => addNodeById(ch.id))
  }

  matched.forEach(root => addNodeById(root.id))

   
  // 4) 扁平 → 树，并在树上补备件
  allRoots.value = buildTree(result)
  totalRoots.value = allRoots.value.length
  pageNum.value = 1
}


/** 扁平数组构建树（并挂上备件） */
function buildTree(rows = []) {
  const filtered = rows.filter(r => r.nodeType !== 'SYSTEM')
  const map = new Map()
  filtered.forEach(f => map.set(f.id, { ...f, children: [] }))

  const roots = []
  filtered.forEach(f => {
    const cur = map.get(f.id)
    if (!f.parentId || !map.has(f.parentId)) {
      roots.push(cur)
    } else {
      map.get(f.parentId).children.push(cur)
    }
  })

  // 为每个根递归补充备件
  roots.forEach(d => attachRealSpares(d))
  return roots
}



/** 当前页数据 */
const treeRows = computed(() => {
  const start = (pageNum.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allRoots.value.slice(start, end)
})



function openEditDevice(row) { console.log('修改设备', row) }
function openAddAssessment(row) { console.log('新增评估', row) }
function handleSizeChange() { pageNum.value = 1 }
function noop() {}

onMounted(() => loadAllDevices())
</script>

<style scoped>
.device-tree-table {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 10px 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.tree-pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
.empty-block {
  height: 600px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
